package com.salt.task;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.salt.entity.IdleAffiliateIncome;
import com.salt.entity.IdleAffiliateMaterial;
import com.salt.entity.IdleAffiliateSyncRecord;
import com.salt.entity.IdleAffiliateCpsIncomeDetail;
import com.salt.entity.IdleAffiliateCpaIncomeDetail;
import com.salt.entity.IdleAffiliateCpaIncome;
import com.salt.mapper.IdleAffiliateIncomeMapper;
import com.salt.mapper.IdleAffiliateMaterialMapper;
import com.salt.mapper.IdleAffiliateSyncRecordMapper;
import com.salt.mapper.IdleAffiliateCpsIncomeDetailMapper;
import com.salt.mapper.IdleAffiliateCpaIncomeDetailMapper;
import com.salt.mapper.IdleAffiliateCpaIncomeMapper;
import com.salt.service.IdleAffiliateCpaCommissionConfigService;
import com.salt.service.IdleAffiliateMaterialService;
import com.salt.service.TaobaoApiService;
import com.salt.service.UserService;
import com.taobao.api.response.AlibabaIdleAffiliateIncomeSummaryResponse;
import com.taobao.api.response.AlibabaIdleAffiliateMaterialQueryResponse;
import com.taobao.api.response.AlibabaIdleAffiliateCpsIncomeDetailsQueryResponse;
import com.taobao.api.response.AlibabaIdleAffiliateCpaIncomeDetailsQueryResponse;
import com.taobao.api.response.AlibabaIdleAffiliateCpaIncomeSummaryResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * 淘宝数据同步定时任务
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TaobaoDataSyncTask {

    private final TaobaoApiService taobaoApiService;
    private final IdleAffiliateIncomeMapper incomeMapper;
    private final IdleAffiliateMaterialMapper materialMapper;
    private final IdleAffiliateSyncRecordMapper syncRecordMapper;
    private final IdleAffiliateCpsIncomeDetailMapper incomeDetailMapper;
    private final IdleAffiliateCpaIncomeDetailMapper cpaIncomeDetailMapper;
    private final IdleAffiliateCpaIncomeMapper cpaIncomeMapper;
    private final UserService userService;
    private final IdleAffiliateMaterialService affiliateMaterialService;
    private final ObjectMapper objectMapper;
    private final IdleAffiliateCpaCommissionConfigService affiliateCpaCommissionConfigService;

    /**
     * 每天凌晨2点执行物料同步
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void syncMaterials() {
        IdleAffiliateSyncRecord syncRecord = new IdleAffiliateSyncRecord();
        syncRecord.setSyncType(1); // 物料同步
        syncRecord.setStatus(0); // 初始状态为失败
        syncRecord.setDataCount(0);
        LocalDateTime now = LocalDateTime.now();
        syncRecord.setCreateTime(now);
        syncRecord.setUpdateTime(now);
        
        try {
            log.info("开始执行物料同步任务");
            
            // 分页获取物料数据
            Long pageSize = 20L;
            Long pageNum = 1L;
            boolean hasMore = true;
            int totalCount = 0;
            
            while (hasMore) {
                log.info("正在同步第{}页物料数据", pageNum);
                
                AlibabaIdleAffiliateMaterialQueryResponse response = taobaoApiService.queryMaterials(
                    1L,  // materialType
                    pageSize,
                    pageNum,
                    null,  // tabName
                    null,  // itemPublisherTime
                    null,  // sellerCreditLevel
                    null,  // filterLevel5Yxp
                    null,  // filterYhb
                    null,  // sellerName
                    null   // keyword
                );
                
                if (response != null && response.isSuccess()) {
                    // 检查是否还有更多数据
                    if (response.getResult() != null && 
                        response.getResult().getResult() != null && 
                        !response.getResult().getResult().isEmpty()) {
                        
                        // 保存物料数据
                        for (AlibabaIdleAffiliateMaterialQueryResponse.MaterialDTO materialDTO : 
                            response.getResult().getResult()) {
                            
                            if (materialDTO != null && materialDTO.getItemInfo() != null 
                                && materialDTO.getItemInfo().getItemBaseInfo() != null 
                                && materialDTO.getItemInfo().getItemBaseInfo().getItemId() != null) {
                                
                                // 检查是否已存在
                                IdleAffiliateMaterial existingMaterial = materialMapper.selectOne(
                                    new LambdaQueryWrapper<IdleAffiliateMaterial>()
                                        .eq(IdleAffiliateMaterial::getItemId, 
                                            materialDTO.getItemInfo().getItemBaseInfo().getItemId())
                                );
                                
                                if (existingMaterial != null) {
                                    // 更新现有记录
                                    updateMaterial(existingMaterial, materialDTO);
                                } else {
                                    // 创建新记录
                                    saveMaterial(materialDTO);
                                }
                                
                                totalCount++;
                            }
                        }
                        
                        pageNum++;
                    } else {
                        hasMore = false;
                    }
                } else {
                    log.error("获取物料数据失败，停止同步");
                    hasMore = false;
                }
                
                // 避免请求过于频繁
                Thread.sleep(1000);
            }
            
            // 更新同步记录
            syncRecord.setStatus(1); // 成功
            syncRecord.setDataCount(totalCount);
            syncRecord.setUpdateTime(LocalDateTime.now());
            syncRecordMapper.insert(syncRecord);
            
            log.info("物料同步任务执行完成，共同步{}条数据", totalCount);
        } catch (Exception e) {
            log.error("物料同步任务执行异常", e);
            // 更新同步记录
            syncRecord.setErrorMsg(e.getMessage());
            syncRecord.setUpdateTime(LocalDateTime.now());
            syncRecordMapper.insert(syncRecord);
        }
    }

    /**
     * 每小时执行一次收入汇总同步
     */
    @Scheduled(cron = "0 0 0/3 * * ?")
    public void syncIncomeSummary() {
        IdleAffiliateSyncRecord syncRecord = new IdleAffiliateSyncRecord();
        syncRecord.setSyncType(2); // 收入同步
        syncRecord.setStatus(0); // 初始状态为失败
        syncRecord.setDataCount(0);
        LocalDateTime now = LocalDateTime.now();
        syncRecord.setCreateTime(now);
        syncRecord.setUpdateTime(now);
        
        try {
            log.info("开始执行收入汇总同步任务");
            
            AlibabaIdleAffiliateIncomeSummaryResponse response = taobaoApiService.getIncomeSummary();
            
            if (response != null && response.isSuccess()) {
                log.info("收入汇总同步成功");
                if (response.getResult() != null && response.getResult().getResult() != null) {
                    AlibabaIdleAffiliateIncomeSummaryResponse.CpsIncomeSummaryDTO result = response.getResult().getResult();
                    log.info("累计收入: {}, 未结算收入: {}, 账户余额: {}", 
                        result.getAccumulatedAmountText(),
                        result.getUnaccountedAmountText(),
                        result.getBalanceText());
                    
                    // 查询是否存在记录
                    IdleAffiliateIncome existingIncome = incomeMapper.selectOne(
                        new LambdaQueryWrapper<IdleAffiliateIncome>()
                            .orderByDesc(IdleAffiliateIncome::getCreateTime)
                            .last("LIMIT 1")
                    );
                    
                    LocalDateTime updateTime = LocalDateTime.now();
                    
                    if (existingIncome != null) {
                        // 更新现有记录
                        existingIncome.setAccumulatedAmount(new BigDecimal(result.getAccumulatedAmountText()));
                        existingIncome.setUnaccountedAmount(new BigDecimal(result.getUnaccountedAmountText()));
                        existingIncome.setBalance(new BigDecimal(result.getBalanceText()));
                        existingIncome.setUpdateTime(updateTime);
                        
                        incomeMapper.updateById(existingIncome);
                        log.info("收入汇总数据更新成功");
                    } else {
                        // 创建新记录
                        IdleAffiliateIncome income = new IdleAffiliateIncome();
                        income.setAccumulatedAmount(new BigDecimal(result.getAccumulatedAmountText()));
                        income.setUnaccountedAmount(new BigDecimal(result.getUnaccountedAmountText()));
                        income.setBalance(new BigDecimal(result.getBalanceText()));
                        income.setCreateTime(updateTime);
                        income.setUpdateTime(updateTime);
                        
                        incomeMapper.insert(income);
                        log.info("收入汇总数据创建成功");
                    }
                    
                    // 更新同步记录
                    syncRecord.setStatus(1); // 成功
                    syncRecord.setDataCount(1);
                    syncRecord.setUpdateTime(updateTime);
                    syncRecordMapper.insert(syncRecord);
                }
            } else {
                log.error("收入汇总同步失败");
                // 更新同步记录
                syncRecord.setErrorMsg(response != null ? response.getSubMsg() : "未知错误");
                syncRecord.setUpdateTime(LocalDateTime.now());
                syncRecordMapper.insert(syncRecord);
            }
        } catch (Exception e) {
            log.error("收入汇总同步任务执行异常", e);
            // 更新同步记录
            syncRecord.setErrorMsg(e.getMessage());
            syncRecord.setUpdateTime(LocalDateTime.now());
            syncRecordMapper.insert(syncRecord);
        }
    }
    
    /**
     * 每小时执行一次佣金明细同步
     */
    @Scheduled(cron = "2 0/1 * * * ?")
    public void syncCpsIncomeDetails() {
        IdleAffiliateSyncRecord syncRecord = new IdleAffiliateSyncRecord();
        syncRecord.setSyncType(3); // 佣金明细同步
        syncRecord.setStatus(0); // 初始状态为失败
        syncRecord.setDataCount(0);
        LocalDateTime now = LocalDateTime.now();
        syncRecord.setCreateTime(now);
        syncRecord.setUpdateTime(now);

        doSyncCpsIncomeDetails(syncRecord, now);
    }

    /**
     * 每小时执行一次佣金明细同步
     */
    @Scheduled(cron = "2 0/2 * * * ?")
    public void newSyncCpsIncomeDetails() {
        IdleAffiliateSyncRecord syncRecord = new IdleAffiliateSyncRecord();
        syncRecord.setSyncType(3); // 佣金明细同步
        syncRecord.setStatus(0); // 初始状态为失败
        syncRecord.setDataCount(0);
        LocalDateTime now = LocalDateTime.now().minusDays(10);

        doSyncCpsIncomeDetails(syncRecord, now);
    }

    private void doSyncCpsIncomeDetails(IdleAffiliateSyncRecord syncRecord, LocalDateTime now) {
        try {
            log.info("开始执行佣金明细同步任务");

            // 获取当前月份
            String currentMonth = now.format(DateTimeFormatter.ofPattern("yyyyMM"));

            // 分页获取佣金明细数据
            Long pageSize = 20L;
            Long pageNum = 1L;
            boolean hasMore = true;
            int totalCount = 0;
            long startTime = now.toLocalDate()
                    .atStartOfDay()
                    .toInstant(ZoneOffset.ofHours(8))  // 北京时间（东八区）
                    .toEpochMilli();

            while (hasMore) {
                log.info("正在同步第{}页佣金明细数据", pageNum);

                AlibabaIdleAffiliateCpsIncomeDetailsQueryResponse response = taobaoApiService.queryCpsIncomeDetails(
                        null,  // createMonth
                    null,           // billState: 0-全部
                    pageSize,
                    pageNum,
                        startTime,         // startCreateTimeStamp
                    null,         // endCreateTimeStamp
                    null,         // startUpdateTime
                    null          // endUpdateTime
                );

                if (response != null && response.isSuccess()) {
                    if (response.getResult() != null &&
                            CollectionUtil.isNotEmpty(response.getResult().getResult()) ) {

                        // 保存佣金明细数据
                        for (AlibabaIdleAffiliateCpsIncomeDetailsQueryResponse.CommissionDetailDTO detailDTO :
                            response.getResult().getResult()) {

                            if (detailDTO != null && detailDTO.getBillId() != null) {
                                // 检查是否已存在
                                IdleAffiliateCpsIncomeDetail existingDetail = incomeDetailMapper.selectOne(
                                    new LambdaQueryWrapper<IdleAffiliateCpsIncomeDetail>()
                                        .eq(IdleAffiliateCpsIncomeDetail::getBillId, detailDTO.getBillId())
                                );
                                IdleAffiliateMaterial affiliateMaterial = affiliateMaterialService.getByItemId(detailDTO.getTradeOrderDTO().getItemId());

                                BigDecimal estimatedCommission =
                                        (affiliateMaterial != null && affiliateMaterial.getEstimatedCommission() != null)
                                                ? affiliateMaterial.getEstimatedCommission()
                                                : BigDecimal.ZERO;
                                if (existingDetail != null) {
                                    // 更新现有记录
                                    updateIncomeDetail(existingDetail, detailDTO,estimatedCommission);
                                } else {
                                    // 创建新记录
                                    saveIncomeDetail(detailDTO,estimatedCommission);
                                }

                                totalCount++;
                            }
                        }
                        pageNum++;
                    } else {
                        hasMore = false;
                    }
                } else {
                    log.error("获取佣金明细数据失败，停止同步");
                    hasMore = false;
                }

                // 避免请求过于频繁
                Thread.sleep(1000);
            }

            // 更新同步记录
            syncRecord.setStatus(1); // 成功
            syncRecord.setDataCount(totalCount);
            syncRecord.setUpdateTime(LocalDateTime.now());
            syncRecordMapper.insert(syncRecord);

            log.info("佣金明细同步任务执行完成，共同步{}条数据", totalCount);
        } catch (Exception e) {
            log.error("佣金明细同步任务执行异常", e);
            // 更新同步记录
            syncRecord.setErrorMsg(e.getMessage());
            syncRecord.setUpdateTime(LocalDateTime.now());
            syncRecordMapper.insert(syncRecord);
        }
    }

    /**
     * 每小时执行一次CPA佣金明细同步
     */
    @Scheduled(cron = "3 0/1 * * * ?")
    public void syncCpaIncomeDetails() {
        IdleAffiliateSyncRecord syncRecord = new IdleAffiliateSyncRecord();
        syncRecord.setSyncType(4); // CPA佣金明细同步
        syncRecord.setStatus(0); // 初始状态为失败
        syncRecord.setDataCount(0);
        LocalDateTime now = LocalDateTime.now();
        syncRecord.setCreateTime(now);
        syncRecord.setUpdateTime(now);

        extracted(syncRecord, now);
    }

    /**
     * 每小时执行一次CPA佣金明细同步
     */
    @Scheduled(cron = "3 0/2 * * * ?")
    public void syncCpaIncomeDetails1() {
        IdleAffiliateSyncRecord syncRecord = new IdleAffiliateSyncRecord();
        syncRecord.setSyncType(4); // CPA佣金明细同步
        syncRecord.setStatus(0); // 初始状态为失败
        syncRecord.setDataCount(0);
        LocalDateTime now = LocalDateTime.now();
        syncRecord.setCreateTime(now);
        syncRecord.setUpdateTime(now);
         now = LocalDateTime.now().minusDays(10);

        extracted(syncRecord,now);
    }

    private void extracted(IdleAffiliateSyncRecord syncRecord, LocalDateTime now) {
        try {
            log.info("开始执行CPA佣金明细同步任务");

            // 分页获取CPA佣金明细数据
            Long pageSize = 20L;
            Long pageNum = 1L;
            boolean hasMore = true;
            int totalCount = 0;
            long startTime = now.toLocalDate()
                    .atStartOfDay()
                    .toInstant(ZoneOffset.ofHours(8))  // 北京时间（东八区）
                    .toEpochMilli();

            while (hasMore) {
                log.info("正在同步第{}页CPA佣金明细数据", pageNum);

                AlibabaIdleAffiliateCpaIncomeDetailsQueryResponse response = taobaoApiService.queryCpaIncomeDetails(
                    null,           // billState: 0-全部
                    pageSize,
                    pageNum,
                        startTime,         // startTime
                    null          // endTime
                );

                if (response != null && response.isSuccess()) {
                    if (response.getResult() != null &&
                            CollectionUtil.isNotEmpty(response.getResult().getResult())) {

                        // 保存CPA佣金明细数据
                        for (AlibabaIdleAffiliateCpaIncomeDetailsQueryResponse.CpaBillDTO detailDTO :
                            response.getResult().getResult()) {

                            if (detailDTO != null && detailDTO.getBillId() != null) {
                                // 检查是否已存在
                                IdleAffiliateCpaIncomeDetail existingDetail = cpaIncomeDetailMapper.selectOne(
                                    new LambdaQueryWrapper<IdleAffiliateCpaIncomeDetail>()
                                        .eq(IdleAffiliateCpaIncomeDetail::getBillId, detailDTO.getBillId())
                                );
                                Integer type = 0;
                                String comment = detailDTO.getComment();
                                String extendInfoJson = detailDTO.getExtendInfo();

                                if (StringUtils.isNotEmpty(extendInfoJson)) {
                                    try {
                                        JsonNode extendInfo = objectMapper.readTree(extendInfoJson);
                                        if (extendInfo.has("user_l1_label") && "U2".equals(extendInfo.get("user_l1_label").asText())) {
                                            type = 3; // 匹配成功，直接赋值，跳过后续 comment 判断
                                        } else {
                                            // extendInfo 存在但不匹配 U2，继续处理 comment
                                            type =handleComment(comment, type);
                                        }
                                    } catch (JsonProcessingException e) {
                                        // 解析失败时，按 comment 处理（或默认值）
                                        type =handleComment(comment, type);
                                    }
                                } else {
                                    // extendInfo 不存在，直接处理 comment
                                    type =handleComment(comment, type);
                                }
                                BigDecimal commissionAmount = affiliateCpaCommissionConfigService.getCommissionAmount(type);

                                if (existingDetail != null) {
                                    // 更新现有记录
                                    updateCpaIncomeDetail(existingDetail, detailDTO,commissionAmount);
                                } else {
                                    // 创建新记录
                                    saveCpaIncomeDetail(detailDTO,commissionAmount);
                                }

                                totalCount++;
                            }
                        }
                        pageNum++;
                    } else {
                        hasMore = false;
                    }
                } else {
                    log.error("获取CPA佣金明细数据失败，停止同步");
                    hasMore = false;
                }

                // 避免请求过于频繁
                Thread.sleep(1000);
            }

            // 更新同步记录
            syncRecord.setStatus(1); // 成功
            syncRecord.setDataCount(totalCount);
            syncRecord.setUpdateTime(LocalDateTime.now());
            syncRecordMapper.insert(syncRecord);

            log.info("CPA佣金明细同步任务执行完成，共同步{}条数据", totalCount);
        } catch (Exception e) {
            log.error("CPA佣金明细同步任务执行异常", e);
            // 更新同步记录
            syncRecord.setErrorMsg(e.getMessage());
            syncRecord.setUpdateTime(LocalDateTime.now());
            syncRecordMapper.insert(syncRecord);
        }
    }

    private Integer handleComment(String comment, Integer type) {
        if (type == 0 && comment != null) { // 只有当 type 未被修改时，才处理 comment
            if ("推荐新用户".equals(comment)) {
                type = 1;
            } else if ("推荐新朋友购买".equals(comment)) {
                type = 2;
            } else if (comment.contains("推荐老朋友")) {
                type = 4;
            }
        }
        return type;
    }
    
    /**
     * 每小时执行一次CPA收入汇总同步
     */
    @Scheduled(cron = "0 0 0/3 * * ?")
    public void syncCpaIncomeSummary() {
        IdleAffiliateSyncRecord syncRecord = new IdleAffiliateSyncRecord();
        syncRecord.setSyncType(5); // CPA收入汇总同步
        syncRecord.setStatus(0); // 初始状态为失败
        syncRecord.setDataCount(0);
        LocalDateTime now = LocalDateTime.now();
        syncRecord.setCreateTime(now);
        syncRecord.setUpdateTime(now);
        
        try {
            log.info("开始执行CPA收入汇总同步任务");
            
            AlibabaIdleAffiliateCpaIncomeSummaryResponse response = taobaoApiService.getCpaIncomeSummary();
            
            if (response != null && response.isSuccess()) {
                log.info("CPA收入汇总同步成功");
                if (response.getResult() != null && response.getResult().getResult() != null) {
                    AlibabaIdleAffiliateCpaIncomeSummaryResponse.CpaIncomeSummaryDTO result = response.getResult().getResult();
                    log.info("累计收入: {}, 未结算收入: {}, 账户余额: {}", 
                        result.getAccumulatedAmountText(),
                        result.getUnaccountedAmountText(),
                        result.getBalanceText());
                    
                    // 查询是否存在记录
                    IdleAffiliateCpaIncome existingIncome = cpaIncomeMapper.selectOne(
                        new LambdaQueryWrapper<IdleAffiliateCpaIncome>()
                            .orderByDesc(IdleAffiliateCpaIncome::getCreateTime)
                            .last("LIMIT 1")
                    );
                    
                    LocalDateTime updateTime = LocalDateTime.now();
                    
                    if (existingIncome != null) {
                        // 更新现有记录
                        existingIncome.setAccumulatedAmount(new BigDecimal(result.getAccumulatedAmountText()));
                        existingIncome.setUnaccountedAmount(new BigDecimal(result.getUnaccountedAmountText()));
                        existingIncome.setBalance(new BigDecimal(result.getBalanceText()));
                        existingIncome.setUpdateTime(updateTime);
                        
                        cpaIncomeMapper.updateById(existingIncome);
                        log.info("CPA收入汇总数据更新成功");
                    } else {
                        // 创建新记录
                        IdleAffiliateCpaIncome income = new IdleAffiliateCpaIncome();
                        income.setAccumulatedAmount(new BigDecimal(result.getAccumulatedAmountText()));
                        income.setUnaccountedAmount(new BigDecimal(result.getUnaccountedAmountText()));
                        income.setBalance(new BigDecimal(result.getBalanceText()));
                        income.setCreateTime(updateTime);
                        income.setUpdateTime(updateTime);
                        
                        cpaIncomeMapper.insert(income);
                        log.info("CPA收入汇总数据创建成功");
                    }
                    
                    // 更新同步记录
                    syncRecord.setStatus(1); // 成功
                    syncRecord.setDataCount(1);
                    syncRecord.setUpdateTime(updateTime);
                    syncRecordMapper.insert(syncRecord);
                }
            } else {
                log.error("CPA收入汇总同步失败");
                // 更新同步记录
                syncRecord.setErrorMsg(response != null ? response.getSubMsg() : "未知错误");
                syncRecord.setUpdateTime(LocalDateTime.now());
                syncRecordMapper.insert(syncRecord);
            }
        } catch (Exception e) {
            log.error("CPA收入汇总同步任务执行异常", e);
            // 更新同步记录
            syncRecord.setErrorMsg(e.getMessage());
            syncRecord.setUpdateTime(LocalDateTime.now());
            syncRecordMapper.insert(syncRecord);
        }
    }
    
    /**
     * 保存物料数据
     */
    private void saveMaterial(AlibabaIdleAffiliateMaterialQueryResponse.MaterialDTO materialDTO) {
        if (materialDTO == null || materialDTO.getItemInfo() == null 
            || materialDTO.getItemInfo().getItemBaseInfo() == null) {
            log.warn("物料数据不完整，无法保存");
            return;
        }
        
        IdleAffiliateMaterial material = new IdleAffiliateMaterial();
        material.setMaterialType(materialDTO.getMaterialType());
        
        // 设置商品基本信息
        AlibabaIdleAffiliateMaterialQueryResponse.ItemBaseInfo baseInfo = 
            materialDTO.getItemInfo().getItemBaseInfo();
        material.setItemId(baseInfo.getItemId());
        material.setItemTitle(baseInfo.getItemTitle());
        material.setItemDesc(baseInfo.getItemDesc());
        material.setCategoryName(baseInfo.getCategoryName());
        material.setStatus(baseInfo.getStatus());
        material.setStatusDesc(baseInfo.getStatusDesc());
        material.setReservePrice(new BigDecimal(baseInfo.getReservePrice()));
        material.setOriginalPrice(new BigDecimal(baseInfo.getOriginalPrice()));
        material.setStuffStatus(baseInfo.getStuffStatus());
        material.setAuctionType(baseInfo.getAuctionType());
        material.setSkuItem(baseInfo.getSkuItem());
        material.setIsFishShop(baseInfo.getIsFishShop());
        material.setUserFishShopGrade(baseInfo.getUserFishShopGrade());
        material.setSellerLevelCode(baseInfo.getSellerLevelCode());
        material.setYhbItem(baseInfo.getYhbItem());
        
        // 设置推广信息
        if (materialDTO.getItemInfo().getItemPromoteInfo() != null) {
            AlibabaIdleAffiliateMaterialQueryResponse.ItemPromoteInfo promoteInfo = 
                materialDTO.getItemInfo().getItemPromoteInfo();
            material.setCommissionRate(new BigDecimal(promoteInfo.getCommissionRate()));
            material.setEstimatedCommission(new BigDecimal(promoteInfo.getEstimatedCommission()));
        }
        
        // 设置优惠券信息
        if (materialDTO.getCouponInfo() != null) {
            material.setCouponId(materialDTO.getCouponInfo().getCouponId());
            material.setCouponName(materialDTO.getCouponInfo().getCouponName());
        }
        
        // 设置时间
        LocalDateTime now = LocalDateTime.now();
        material.setCreateTime(now);
        material.setUpdateTime(now);
        
        materialMapper.insert(material);
    }
    
    /**
     * 更新物料数据
     */
    private void updateMaterial(IdleAffiliateMaterial existingMaterial, 
        AlibabaIdleAffiliateMaterialQueryResponse.MaterialDTO materialDTO) {
        
        if (materialDTO == null || materialDTO.getItemInfo() == null 
            || materialDTO.getItemInfo().getItemBaseInfo() == null) {
            log.warn("物料数据不完整，无法更新");
            return;
        }
        
        // 更新商品基本信息
        AlibabaIdleAffiliateMaterialQueryResponse.ItemBaseInfo baseInfo = 
            materialDTO.getItemInfo().getItemBaseInfo();
        existingMaterial.setItemTitle(baseInfo.getItemTitle());
        existingMaterial.setItemDesc(baseInfo.getItemDesc());
        existingMaterial.setCategoryName(baseInfo.getCategoryName());
        existingMaterial.setStatus(baseInfo.getStatus());
        existingMaterial.setStatusDesc(baseInfo.getStatusDesc());
        existingMaterial.setReservePrice(new BigDecimal(baseInfo.getReservePrice()));
        existingMaterial.setOriginalPrice(new BigDecimal(baseInfo.getOriginalPrice()));
        existingMaterial.setStuffStatus(baseInfo.getStuffStatus());
        existingMaterial.setAuctionType(baseInfo.getAuctionType());
        existingMaterial.setSkuItem(baseInfo.getSkuItem());
        existingMaterial.setIsFishShop(baseInfo.getIsFishShop());
        existingMaterial.setUserFishShopGrade(baseInfo.getUserFishShopGrade());
        existingMaterial.setSellerLevelCode(baseInfo.getSellerLevelCode());
        existingMaterial.setYhbItem(baseInfo.getYhbItem());
        
        // 更新推广信息
        if (materialDTO.getItemInfo().getItemPromoteInfo() != null) {
            AlibabaIdleAffiliateMaterialQueryResponse.ItemPromoteInfo promoteInfo = 
                materialDTO.getItemInfo().getItemPromoteInfo();
            existingMaterial.setCommissionRate(new BigDecimal(promoteInfo.getCommissionRate()));
           // existingMaterial.setEstimatedCommission(new BigDecimal(promoteInfo.getEstimatedCommission()));
        }
        
        // 更新优惠券信息
        if (materialDTO.getCouponInfo() != null) {
            existingMaterial.setCouponId(materialDTO.getCouponInfo().getCouponId());
            existingMaterial.setCouponName(materialDTO.getCouponInfo().getCouponName());
        }
        
        // 更新时间
        existingMaterial.setUpdateTime(LocalDateTime.now());
        
        materialMapper.updateById(existingMaterial);
    }
    
    /**
     * 保存佣金明细数据
     */
    private void saveIncomeDetail(AlibabaIdleAffiliateCpsIncomeDetailsQueryResponse.CommissionDetailDTO detailDTO, BigDecimal estimatedCommission) {
        if (detailDTO == null || detailDTO.getBillInfo() == null) {
            log.warn("佣金明细数据不完整，无法保存");
            return;
        }
        
        IdleAffiliateCpsIncomeDetail detail = new IdleAffiliateCpsIncomeDetail();
        
        // 设置账单信息
        AlibabaIdleAffiliateCpsIncomeDetailsQueryResponse.BillDTO billInfo = detailDTO.getBillInfo();
        detail.setBillId(detailDTO.getBillId());
        detail.setPlainBillId(detailDTO.getPlainBillId());
        detail.setSubPublisherId(billInfo.getSubPublisherId());
        detail.setBillState(billInfo.getState().intValue());
        detail.setBillStateText(billInfo.getStateText());

        // 添加空值判断
        if (StringUtils.isNotBlank(billInfo.getSettleAmountText())) {
            detail.setSettleAmount(new BigDecimal(billInfo.getSettleAmountText()));
        }

        if (StringUtils.isEmpty(billInfo.getAssessAmountText()) || (new BigDecimal(billInfo.getAssessAmountText())).compareTo(BigDecimal.ZERO) > 0) {
            estimatedCommission = new BigDecimal("0.0");
        }

        if (StringUtils.isNotBlank(billInfo.getAssessAmountText())) {
            detail.setAssessAmount(new BigDecimal(billInfo.getAssessAmountText()).add(estimatedCommission));
            detail.setSettleAmount(new BigDecimal(billInfo.getAssessAmountText()));
        }

// 如果状态为2，更新用户余额
        if ((billInfo.getState().intValue() == 1 || billInfo.getState().intValue() == 2)&&StringUtils.isNotBlank(billInfo.getAssessAmountText())) {
            userService.updateBalance(billInfo.getSubPublisherId(),  new BigDecimal(billInfo.getAssessAmountText()).add(estimatedCommission));
        }

        detail.setAccountingTime(billInfo.getAccountingTime());
        detail.setAccountingWriteOffTime(billInfo.getAccountingWriteOffTime());
        
        // 设置订单信息
        if (detailDTO.getTradeOrderDTO() != null) {

            AlibabaIdleAffiliateCpsIncomeDetailsQueryResponse.TradeOrderDTO orderDTO = detailDTO.getTradeOrderDTO();
            detail.setItemId(orderDTO.getItemId());
            detail.setItemTitle(orderDTO.getItemTitle());
            detail.setItemPicUrl(orderDTO.getItemPicUrl());
            detail.setOrderId(orderDTO.getOrderId());
            detail.setOrderState(orderDTO.getStateCode().intValue());
            detail.setOrderStateDesc(orderDTO.getStateDesc());
            detail.setOrderCreateTime(orderDTO.getGmtCreate());
            detail.setOrderPayTime(orderDTO.getPayTime());
            detail.setOrderEndTime(orderDTO.getEndTime());

            // 添加空值判断
            if (StringUtils.isNotBlank(orderDTO.getActualPaidFee())) {
                detail.setOrderActualPaidFee(new BigDecimal(orderDTO.getActualPaidFee()));
            }
            if (StringUtils.isNotBlank(orderDTO.getPartConfirmFee())) {
                detail.setOrderPartConfirmFee(new BigDecimal(orderDTO.getPartConfirmFee()));
            }
            if (StringUtils.isNotBlank(orderDTO.getCouponDiscountFee())) {
                detail.setOrderCouponDiscountFee(new BigDecimal(orderDTO.getCouponDiscountFee()));
            }
        }
        
        detail.setDeeplink(detailDTO.getDeeplink());
        
        // 设置时间
        LocalDateTime now = LocalDateTime.now();
        detail.setCreateTime(now);
        detail.setUpdateTime(now);
        
        incomeDetailMapper.insert(detail);
    }
    
    /**
     * 更新佣金明细数据
     */
    private void updateIncomeDetail(IdleAffiliateCpsIncomeDetail existingDetail,
                                    AlibabaIdleAffiliateCpsIncomeDetailsQueryResponse.CommissionDetailDTO detailDTO, BigDecimal estimatedCommission) {
        
        if (detailDTO == null || detailDTO.getBillInfo() == null) {
            log.warn("佣金明细数据不完整，无法更新");
            return;
        }
        
        // 设置账单信息
        AlibabaIdleAffiliateCpsIncomeDetailsQueryResponse.BillDTO billInfo = detailDTO.getBillInfo();
        existingDetail.setSubPublisherId(billInfo.getSubPublisherId());
        existingDetail.setBillState(billInfo.getState().intValue());
        existingDetail.setBillStateText(billInfo.getStateText());
        
        // 添加空值判断
        if (StringUtils.isNotBlank(billInfo.getSettleAmountText())) {
            existingDetail.setSettleAmount(new BigDecimal(billInfo.getSettleAmountText()));
        }
        if (StringUtils.isEmpty(billInfo.getAssessAmountText()) || (new BigDecimal(billInfo.getAssessAmountText())).compareTo(BigDecimal.ZERO) > 0) {
            estimatedCommission = new BigDecimal("0.0");
        }

        if (StringUtils.isNotBlank(billInfo.getAssessAmountText())) {
            existingDetail.setAssessAmount(new BigDecimal(billInfo.getAssessAmountText()).add(estimatedCommission));
            existingDetail.setSettleAmount(new BigDecimal(billInfo.getAssessAmountText()));
        }


        // 如果状态从非1,2变为1,2，需要增加余额
        if ((existingDetail.getBillState() != 1 && existingDetail.getBillState() != 2 ) &&
                (billInfo.getState().intValue() == 1 || billInfo.getState().intValue() == 2)) {
            userService.updateBalance(billInfo.getSubPublisherId(), new BigDecimal(billInfo.getAssessAmountText()).add(estimatedCommission));
        }
        existingDetail.setAccountingTime(billInfo.getAccountingTime());
        existingDetail.setAccountingWriteOffTime(billInfo.getAccountingWriteOffTime());
        
        // 设置订单信息
        if (detailDTO.getTradeOrderDTO() != null) {
            AlibabaIdleAffiliateCpsIncomeDetailsQueryResponse.TradeOrderDTO orderDTO = detailDTO.getTradeOrderDTO();


            existingDetail.setItemId(orderDTO.getItemId());
            existingDetail.setItemTitle(orderDTO.getItemTitle());
            existingDetail.setItemPicUrl(orderDTO.getItemPicUrl());
            existingDetail.setOrderId(orderDTO.getOrderId());
            existingDetail.setOrderState(orderDTO.getStateCode().intValue());
            existingDetail.setOrderStateDesc(orderDTO.getStateDesc());
            existingDetail.setOrderCreateTime(orderDTO.getGmtCreate());
            existingDetail.setOrderPayTime(orderDTO.getPayTime());
            existingDetail.setOrderEndTime(orderDTO.getEndTime());


            // 添加空值判断
            if (StringUtils.isNotBlank(orderDTO.getActualPaidFee())) {
                existingDetail.setOrderActualPaidFee(new BigDecimal(orderDTO.getActualPaidFee()));
            }
            if (StringUtils.isNotBlank(orderDTO.getPartConfirmFee())) {
                existingDetail.setOrderPartConfirmFee(new BigDecimal(orderDTO.getPartConfirmFee()));
            }
            if (StringUtils.isNotBlank(orderDTO.getCouponDiscountFee())) {
                existingDetail.setOrderCouponDiscountFee(new BigDecimal(orderDTO.getCouponDiscountFee()));
            }
        }
        
        existingDetail.setDeeplink(detailDTO.getDeeplink());
        
        // 更新时间
        existingDetail.setUpdateTime(LocalDateTime.now());
        
        incomeDetailMapper.updateById(existingDetail);
    }
    
    /**
     * 保存CPA佣金明细数据
     */
    private void saveCpaIncomeDetail(AlibabaIdleAffiliateCpaIncomeDetailsQueryResponse.CpaBillDTO detailDTO, BigDecimal commissionAmount) {
        if (detailDTO == null) {
            log.warn("CPA佣金明细数据不完整，无法保存");
            return;
        }
        
        IdleAffiliateCpaIncomeDetail detail = new IdleAffiliateCpaIncomeDetail();
        detail.setBillId(detailDTO.getBillId());
        detail.setSubPublisherId(detailDTO.getSubPublisherId());
        detail.setInviteeId(detailDTO.getInviteeId());
        detail.setCampaignId(detailDTO.getCampaignId());
        detail.setState(detailDTO.getState().intValue());
        detail.setStateText(detailDTO.getStateText());
        detail.setAmount(commissionAmount);
        detail.setAffiliateAmount(new BigDecimal(detailDTO.getAmount()));
        detail.setAmountCalculationFormula(detailDTO.getAmountCalculationFormula());
        detail.setComment(detailDTO.getComment());
        detail.setExtendInfo(detailDTO.getExtendInfo());

        detail.setCreateTime(detailDTO.getCreateTime());
        detail.setUpdateTime(detailDTO.getUpdateTime());
        
        cpaIncomeDetailMapper.insert(detail);

        // 如果状态为2，更新用户余额
        if (detailDTO.getState().intValue() == 1 || detailDTO.getState().intValue() == 2 ) {
            userService.updateBalance(detailDTO.getSubPublisherId(), commissionAmount);
        }
    }
    
    /**
     * 更新CPA佣金明细数据
     */
    private void updateCpaIncomeDetail(IdleAffiliateCpaIncomeDetail existingDetail,
                                       AlibabaIdleAffiliateCpaIncomeDetailsQueryResponse.CpaBillDTO detailDTO, BigDecimal commissionAmount) {
        
        if (detailDTO == null) {
            log.warn("CPA佣金明细数据不完整，无法更新");
            return;
        }

        // 如果状态从非1,2变为1,2，需要增加余额
        if ((existingDetail.getState() != 1 && existingDetail.getState() != 2 ) &&
            (detailDTO.getState().intValue() == 1 || detailDTO.getState().intValue() == 2 )) {
            userService.updateBalance(detailDTO.getSubPublisherId(), commissionAmount);
            log.info("用户{}状态变更,{}，用户实际获得{}",
                    detailDTO.getSubPublisherId(),detailDTO.getState().intValue(), commissionAmount);
        }

        
        existingDetail.setSubPublisherId(detailDTO.getSubPublisherId());
        existingDetail.setInviteeId(detailDTO.getInviteeId());
        existingDetail.setCampaignId(detailDTO.getCampaignId());
        existingDetail.setState(detailDTO.getState().intValue());
        existingDetail.setStateText(detailDTO.getStateText());
        existingDetail.setAmount(commissionAmount);
        existingDetail.setAffiliateAmount(new BigDecimal(detailDTO.getAmount()));
        existingDetail.setAmountCalculationFormula(detailDTO.getAmountCalculationFormula());
        existingDetail.setComment(detailDTO.getComment());
        existingDetail.setExtendInfo(detailDTO.getExtendInfo());

        existingDetail.setCreateTime(detailDTO.getCreateTime());
        existingDetail.setUpdateTime(detailDTO.getUpdateTime());

        cpaIncomeDetailMapper.updateById(existingDetail);
    }

} 